package com.tcs.test.netty.client.channel;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.SocketAddress;
import java.nio.charset.Charset;

public class ClientOutChannel extends ChannelOutboundHandlerAdapter {

    private final Logger logger = LoggerFactory.getLogger(ClientOutChannel.class);

    @Override
    public void bind(ChannelHandlerContext ctx, SocketAddress localAddress, ChannelPromise promise) throws Exception {
        logger.info("localAddress : {} " , localAddress.toString());
        ByteBuf byteBuf = Unpooled.copiedBuffer("客户端绑定", Charset.defaultCharset());
        ctx.write(byteBuf);
        ctx.flush();
    }

    @Override
    public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) throws Exception {
        logger.info("connect : {} " , remoteAddress.toString());
        ByteBuf byteBuf = Unpooled.copiedBuffer("客户端链接", Charset.forName("UTF-8"));
        ctx.write(byteBuf);
        ctx.flush();
    }

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        logger.info("write : {} " , msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("" , cause);
    }
}
